
package jwww.ui;

import java.io.IOException;
import java.util.Properties;

import jwww.ml.XML;
import jwww.service.Service;
import jwww.service.WebServer;

import org.apache.log4j.*;

public class Main
{
  // Default settings:
  static String serviceClassName = "jwww.handlers.SimpleServer";
  static int port = 8080;
  static String logfile = "/dev/stdout";
  static boolean logtrace = false;

  public static void main(String[] args)
  {
    XML.init();

    scanProperties();

    setupLogging(logfile, logtrace);

    Service service = loadService(serviceClassName);
    WebServer ws = new WebServer(service, port);
    ws.start();
  }

  static void scanProperties()
  {
    Properties props = System.getProperties();
    String t = null;
    try
    {
      t = props.getProperty("jwww.service.class");
      if (t != null)
        serviceClassName = t;
      t = props.getProperty("jwww.port");
      if (t != null)
        port = Integer.parseInt(t);
      t = props.getProperty("jwww.log.file");
      if (t != null)
        logfile = t;
      t = props.getProperty("jwww.log.trace");
      if (t != null)
        logtrace = Boolean.parseBoolean(t);
    }
    catch (NumberFormatException e)
    {
      System.out.println("Not a number: " + t);
      System.exit(1);
    }
  }

  @SuppressWarnings("unchecked")
  static Service loadService(String name)
  {
    Service service = null;
    try
    {
      Class<Service> clazz = (Class<Service>) Class.forName(name);
      service = clazz.newInstance();
    }
    catch (ClassCastException e)
    {
      e.printStackTrace();
      System.exit(1);
    }
    catch (ClassNotFoundException e)
    {
      e.printStackTrace();
      System.exit(1);
    }
    catch (InstantiationException e)
    {
      e.printStackTrace();
    }
    catch (IllegalAccessException e)
    {
      e.printStackTrace();
    }

    return service;
  }

  static Logger getLogger()
  {
    return Logger.getLogger("JWWW");
  }

  private static Logger setupLogging(String logfile, boolean logtrace)
  {
    Logger logger = getLogger();
    setupLoggingToFile(logger, logfile, logtrace);
    // Even if logging is disabled, this must be valid:
    return logger;
  }

  private static void setupLoggingToFile(Logger stcLogger, String logfile, boolean trace)
  {
    Layout layout = new PatternLayout("%-5p %m%n");
    boolean append = false;
    try
    {
      FileAppender appender = new FileAppender(layout, logfile, append);
      Level threshold;
      if (trace) {
        threshold = Level.TRACE;
      } else {
        threshold = Level.DEBUG;
      }
      appender.setThreshold(threshold);
      stcLogger.addAppender(appender);
      stcLogger.setLevel(threshold);
    }
    catch (IOException e)
    {
      System.out.println(e.getMessage());
      System.exit(1);
    }
  }

}
